package edu.taru.office.controller;

import edu.taru.office.common.Constants;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * 身份认证和授权类
 */
@Controller
public class AuthcController {


    /**
     * 登录
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping("/authc/login")
    public String    login(String username , String password , Model model ,HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,
                password);
        String  error ="";
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            error = "用户名/密码错误";
        }catch (IncorrectCredentialsException e){
            error = "用户名/密码错误";
        }catch (ExcessiveAttemptsException e){
            error = "登录失败多次，账户锁定10分钟";
        }catch (LockedAccountException e){
            error = "账户被管理员锁定，无法登录";
        }catch (AuthenticationException  e){
            error = "其他错误：" + e.getMessage();
        }
        if ( !error.equals("")) {// 出错了，返回登录页面
            model.addAttribute(Constants.LOGIN_ERROR_KEY, error);
            return "login";
        }
        session.setAttribute(Constants.LOGIN_USER_KEY,subject.getSession().getAttribute(Constants.LOGIN_USER_KEY));
        return "redirect:/view/index";
    }


    /**
     * 注销
     * @return
     */
    @RequestMapping("/authc/logout")
    public String    logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return  "login";
    }





    /**
     * 修改密码
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/authc/modify")
    public Object    modify(String username,String password){

        return null;
    }

    /**
     * 短信发送
     * @param usernane  用户名就是电话
     * @return
     */
    @RequestMapping("/authc/send")
    public Object   send(String usernane ){
        return null;
    }


    /**
     * 验证短信验证码是否有效
     * @param username
     * @param checkcode
     * @return
     */
    @RequestMapping("/authc/isValid")
    public Object   isValid(String username, String checkcode){
        return null;
    }
}
